package com.ruoyi.file.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Author:cgChen
 * Date:2022/07/09 17:49
 * Description:文件下载
 */
public class FileSaveUrlAsUtils {
    public static void main(String[] args) throws Exception {
        String url ="http://47.104.195.177:9400/statics/2022/06/30/3e3768511975410bb3d39880a45bc3a5_20220630095031A014.jpg";
        File file=UrltoFile(url);
        System.out.println(file);
    }
    //将Url转换为File
    public static File UrltoFile(String url) throws Exception {
        HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
        httpUrl.connect();
        InputStream ins=httpUrl.getInputStream();
        File file = new File("");//System.getProperty("java.io.tmpdir")缓存
        if (file.exists()) {
            file.delete();//如果缓存中存在该文件就删除
        }
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        int len = 8192;
        byte[] buffer = new byte[len];
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return file;

    }
    //将File对象转换为byte[]的形式
    public static byte[] FileTobyte(File file){
        FileInputStream fileInputStream = null;
        byte[] imgData = null;
        try {
            imgData = new byte[(int) file.length()];
            //read file into bytes[]
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(imgData);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return imgData;
    }
}
